package cn.zn.framework.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpStatus;
import cn.zn.base.common.constant.Constants;
import cn.zn.base.exception.CustomException;
import cn.zn.framework.bean.LoginUser;
import cn.zn.user.entity.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Date;

/**
 * 安全服务工具类
 *
 * @author zn-admin
 */
public class SecurityUtil {

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new CustomException(HttpStatus.HTTP_UNAUTHORIZED, "获取用户账户异常");
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new CustomException(HttpStatus.HTTP_UNAUTHORIZED, "获取用户信息异常");
        }
    }

    /**
     * 获取用户
     **/
    public static SysUser getTheUser() {
        try {
            LoginUser loginUser = getLoginUser();
            return loginUser.getTheUser();
        } catch (Exception e) {
            throw new CustomException(HttpStatus.HTTP_UNAUTHORIZED, "获取用户信息异常");
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成单点登录密码
     *
     * @param username 用户名
     * @return 结果
     */
    public static String getSsoPassword(String username) {
        String codeMd5 = SecureUtil.md5(username);
        Date date = DateUtil.date();
        String year = DateUtil.format(date, "yyyy");
        String month = DateUtil.format(date, "MM");
        String day = DateUtil.format(date, "dd");
        String dateStr = year + Constants.SSO_SALT + month + Constants.SSO_SALT + day;
        return SecureUtil.md5(dateStr + codeMd5);
    }

}
